package com.by.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import static org.springframework.cloud.gateway.support.GatewayToStringStyler.filterToStringCreator;

@Slf4j
@Component
public class LogTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
                Integer timespan = Integer.parseInt(value);
                long start = System.currentTimeMillis();

                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    long end = System.currentTimeMillis();
                    long time = end - start;
                    if (time > timespan * 1000) {
                        log.debug("{}还耗时{}", request.getURI(), time);
                    }
                }));
            }
            @Override
            public String toString() {
                return filterToStringCreator(LogTimeGatewayFilterFactory.this)
                        .append(config.getName(), config.getValue()).toString();
            }
        };
    }
}
